package org.obm.lmtp.impl;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderAdapter;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.obm.mina.LineBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MinaLmtpDecoder extends ProtocolDecoderAdapter {
	private final LineBuffer cmd = new LineBuffer(132);
	private LineBuffer data;

	@SuppressWarnings("unused")
	private static final Logger logger = LoggerFactory.getLogger(MinaLmtpDecoder.class);
	
	MinaLmtpDecoder() {
	}

	public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) {
		java.nio.ByteBuffer bb = in.buf();
		while (bb.hasRemaining()) {
			if (data != null) {
				// Receiving LMTP data...
				if (data.parse(bb)) {
					out.write(data);
					if (data.matches(".\r\n")) {
						data = null;
					} else {
						// Assume subsequent lines are of the same size
						data = new LineBuffer(data.size());
					}
				}
			} else if (cmd.parse(bb)) {
				String line = cmd.toString().trim();
				out.write(line);
				cmd.reset();
				if ("DATA".equalsIgnoreCase(getCommand(line))) {
					data = new LineBuffer();
				}
			}
		}
	}

	private static String getCommand(String line) {
		int i = line.indexOf(' ');
		return i > 0 ? line.substring(0, i) : line;
	}
}
